CREATE PROCEDURE [dbo].[SessionSave] 
@Id					UNIQUEIDENTIFIER,
@UserId				UNIQUEIDENTIFIER,
@Length				INT,
@LastAccessedTime	DATETIME,
@LoginTime			DATETIME

AS

DECLARE  @ROWCOUNT AS INT 
DECLARE  @ERROR    AS INT
-- Check whether already record present --
UPDATE Session
SET	
	UserId           	= ISNULL(@UserId,UserId),
	LastAccessedTime    = ISNULL(@LastAccessedTime,LastAccessedTime),
	LoginTime			= ISNULL(@LoginTime,LoginTime)
WHERE  
  	[Id]= @Id

SELECT @ROWCOUNT =  @@ROWCOUNT,@ERROR = @@ERROR

IF @ERROR<>0 
BEGIN
	RAISERROR('ERROR::SessionSave',16,1)
END

IF @RowCount  > 0
BEGIN
	RETURN @RowCount 
END

-- Insert into Session --
INSERT INTO Session (Id, UserId, Length, LastAccessedTime, LoginTime)
VALUES (@Id, @UserId, @Length, @LastAccessedTime, @LoginTime)

SELECT @RowCount =@@ROWCOUNT,@Error=@@ERROR

IF @Error<>0
BEGIN
RAISERROR('ERROR::SessionSave',16,1)
END

RETURN @RowCount
